import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
import qs from 'qs'
const request = axios.create({
  // 配置选项
  // baseURL,
  // timeout
})

function redirectLogin () {
  router.push({
    name: 'login',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}
function refreshToken () {
  return axios.create()({
    method: 'post',
    url: '/front/user/refresh_token',
    data: qs.stringify({
      refreshtoken: store.state.user.refresh_token
    })
  })
}
// 请求拦截器
request.interceptors.request.use(
  function (config) {
    // 我们就在这里通过改写 config 配置信息来实现业务功能的统一处理
    const { user } = store.state
    if (user && user.access_token) {
      config.headers.Authorization = user.access_token
    }

    // 注意：这里一定要返回 config，否则请求就发不出去了
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
let isRfreshing = false
let requests: any[] = []
request.interceptors.response.use(
  function (response) {
    return response
  }, async function (error) {
    if (error.response) {
      const { status } = error.response
      if (status === 400) {
        Message.error('请求参数错误')
      } else if (status === 401) {
        if (!store.state.user) {
          redirectLogin()
          return Promise.reject(error)
        }
        // 刷新Token
        if (!isRfreshing) {
          isRfreshing = true
          return refreshToken().then(res => {
            if (!res.data.success) {
              throw new Error('刷新Token失败')
            }
            // 重新设置用户信息
            store.commit('setUser', res.data.content)
            // 重新发送请求
            requests.forEach(cb => cb())
            // 重置 requests数组
            requests = []
            // 重新发送请求
            return request(error.config)
          }).catch(err => {
            console.log(err)
            store.commit('setUser', null)
            redirectLogin()
            return Promise.reject(error)
          })
        }
        // 挂起正在发的请求
        return new Promise(resolve => {
          requests.push(() => {
            resolve(request(error.config))
          })
        })
      } else if (status === 403) {
        Message.error('没有权限,请联系管理员')
      } else if (status === 404) {
        Message.error('请求的资源不存在')
      } else if (status >= 500) {
        Message.error('服务端错误,请联系管理员')
      }
    } else if (error.request) {

    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message)
    }
    console.log(error.config)
    return Promise.reject(error)
  }
)

export default request
